#用于读取项目目录下的yaml_name.db
import yaml  ,os,sys  ,json                             #第三方模块yaml          需要下载  是一个配置文件解析的第三方模块
project_dir_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  #项目路径
sys.path.append(project_dir_path)           #将项目路径添加到环境中   使得python可以导包
from db.tool_sqlite2 import base_db
class yaml_config:
    def __init__(self,project_path,default_name='_default'):
        self.config_name=None
        self.project_path=project_path
        self.default_name=default_name
        self.config_db_obj=base_db(db_data={'yaml_name':{'id': {'主键':  True,'字段类型':  'INTEGER','自增长':  True},'key': {'唯一索引':  True,'字段类型': 'TEXT'},'val': {'字段类型': 'TEXT'}}},db_dir_path=project_dir_path)
    def get(self):
        try:
            res=self.config_db_obj.get(select_field=['val'],condition_field=[['key','yaml_name']])
            res=res['data'][0]['val']
            config_dir=project_dir_path+os.sep+'config'
            lst=[os.path.splitext(item)[0]  for item in os.listdir(config_dir)  ]
            if res not in lst:
                yaml_obj.set(self.default_name)
            res=self.config_db_obj.get(select_field=['val'],condition_field=[['key','yaml_name']])
            res=res['data'][0]['val']
        except:
            self.config_db_obj.post(info={'key':'yaml_name','val':self.default_name})
            res=self.config_db_obj.get(select_field=['val'],condition_field=[['key','yaml_name']])
            res=res['data'][0]['val']
        return res
    def set(self,val,key='yaml_name'):
        self.config_db_obj.put(put_field_dct={'val':val},condition_field=[['key','yaml_name']])
    def read_config(self,config_name=None): 
        if config_name is None:config_name=self.get()                                                
        #加载配置文件
        yaml_path=project_dir_path+os.sep+'config'+os.sep+config_name+'.yaml'
        if os.path.isfile(yaml_path)is not True:
            raise Exception('配置文件路径错误:'+str(yaml_path))
        with open(yaml_path, 'r',encoding='utf-8') as f:
            config = yaml.load(f, Loader=yaml.FullLoader)
        return config
if __name__=='__main__':
    
    #读取当前使用的配置
    yaml_obj=yaml_config(r'C:\Users\12751\桌面\work_space\Immortal_flower_project')
    config = yaml_obj.read_config()
    print(config)
    # # 将dict数据转换为YAML字符串  
    # yaml_data = yaml.dump(config, allow_unicode=True, sort_keys=False, indent=4)  
    
    # # 将YAML字符串写入文件  
    # with open('output.yaml', 'w',encoding='utf-8') as yaml_file:  
    #     yaml_file.write(yaml_data)